package com.xuzimian.global.demo.spring.security.oauth2.client.bootutils;


import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * 备注：从Spring boot autoconfigure 抄过来的源码
 * Default implementation of {@link AuthoritiesExtractor}. Extracts the authorities from
 * the map with the key {@code authorities}. If no such value exists, a single
 * {@code ROLE_USER} authority is returned.
 *
 * @author Dave Syer
 * @since 1.3.0
 */
public class FixedAuthoritiesExtractor implements AuthoritiesExtractor {

    private static final String AUTHORITIES = "authorities";

    @Override
    public List<GrantedAuthority> extractAuthorities(Map<String, Object> map) {
        String authorities = "ROLE_USER";
        if (map.containsKey(AUTHORITIES)) {
            authorities = asAuthorities(map.get(AUTHORITIES));
        }
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authorities);
    }

    private String asAuthorities(Object object) {
        if (object instanceof Collection) {
            return StringUtils.collectionToCommaDelimitedString((Collection<?>) object);
        }
        if (ObjectUtils.isArray(object)) {
            return StringUtils.arrayToCommaDelimitedString((Object[]) object);
        }
        return object.toString();
    }

}
